<!-- src/components/UploadImage.vue -->
<template>
  <div class="upload-image">
    <el-upload
      action=""
      list-type="picture-card"
      :auto-upload="false"
      :file-list="fileList"
      :on-change="handleChange"
      :on-remove="handleRemove"
      :on-preview="handlePreview"
      :limit="1"
    >
      <el-icon><Plus /></el-icon>
    </el-upload>

    <!-- 放大预览 -->
    <el-image-viewer v-if="showViewer" :url-list="[previewUrl]" @close="showViewer = false" />
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { uploadFile as uploadApi } from '@/api/upload' // ① 重命名避免冲突
import type { UploadFile } from 'element-plus'

/* ********  双向绑定  ******** */
const props = defineProps<{
  modelValue: string // 外部传入的线上 url
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', v: string): void
}>()

/* ********  内部状态  ******** */
const fileList = ref<UploadFile[]>([])
const previewUrl = ref('') // 本地预览地址
const showViewer = ref(false)

/* 回显：外部 url -> 显示图片 */
watch(
  () => props.modelValue,
  val => {
    if (val) {
      fileList.value = [{ name: 'image', url: val } as UploadFile]
      previewUrl.value = val
    } else {
      fileList.value = []
      previewUrl.value = ''
    }
  },
  { immediate: true }
)

/* 选完立即上传 */
async function handleChange(uploadFile: UploadFile) {
  const file = uploadFile.raw!
  previewUrl.value = URL.createObjectURL(file) // 本地预览
  const { url } = await uploadApi(file)
  if (url) {
    emit('update:modelValue', url)
    ElMessage.success('上传成功')
  } else {
    throw new Error('上传失败：未获取到图片URL')
  }
}

function handleRemove() {
  emit('update:modelValue', '')
}

function handlePreview() {
  showViewer.value = true
}
</script>

<style scoped>
.upload-image :deep(.el-upload--picture-card) {
  width: 120px;
  height: 120px;
}
</style>
